package HW5;



import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client1 {
    public static void main(String[] args) throws IOException {
        Socket s = null;
        Scanner sc = null;
        BufferedReader br  = null;
        PrintStream ps = null;
        FileInputStream fis = null;
        OutputStream os = null;
        File file = new File("/Users/mac/Desktop/test1.txt");
        String fileName = file.getName();
        try {

            s = new Socket("localhost", 8080);
            sc = new Scanner(System.in);
            //读取客户端的返回信息
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());
            fis = new FileInputStream(file);
            os = s.getOutputStream();

            while(true) {
                System.out.println("请输入:");
                String st = sc.nextLine();
                ps.println(st);
                System.out.println("内容已发送");
                if("bye".equals(st)){
                    System.out.println("断开链接");
                    break;
                }
                if("upload".equalsIgnoreCase(st)){
                    //写入文件名字到流里
                    //ps.write(fileName.getBytes());
                    //发送文件内容信息
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while((len=fis.read(buf))!=-1){
                        os.write(buf,0,len);
                    }
                    continue;
                }
                String st2 = br.readLine();
                System.out.println("来自服务器的信息:" + " " + st2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                assert s != null;
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(null!=s){
                s.close();
            }
            if(null!=br){
                br.close();
            }
            if(null!=ps){
                ps.close();
            }
            if(null!=fis){
                fis.close();
            }
            if(null != os){
                os.close();
            }
        }

    }
}
